package com.nineclock.common.filter;

import cn.hutool.core.lang.Chain;
import cn.hutool.core.util.StrUtil;
import com.nineclock.common.entity.UserInfo;
import com.nineclock.common.utils.CurrentUserHolder;
import com.nineclock.common.utils.JsonUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.io.Reader;

@WebFilter(filterName = "currentUserFilter" ,urlPatterns = "/*")
public class CurrentUserFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            //        获取上下文
            SecurityContext context = SecurityContextHolder.getContext();
//        获取权限信息
            Authentication authentication = context.getAuthentication();
//        获取当前用户信息，存储到TreadLocal
            String nameJSONStr = authentication.getName();

            if(StrUtil.isNotEmpty(nameJSONStr) && !"anonymousUser".equals(nameJSONStr)){
                UserInfo userInfo = JsonUtils.toBean(nameJSONStr, UserInfo.class);
                CurrentUserHolder.set(userInfo);
            }

            filterChain.doFilter(servletRequest,servletResponse);
        } catch (Exception e){
            e.printStackTrace();
        }  finally{
//                移除TreadLocal中的用户信息
                CurrentUserHolder.remove();
        }

//        filterChain.doFilter(servletRequest,servletResponse);

    }
}
